var canvas
var ctx = null

const HEIGHT = 600

const WIDTH = 600

const OffsetLeft = 50
const OffsetTop = 50

const ArrowWidth = 6
const ArrowHeight = 10

// 折线点的事件集合
var rectEvent = []

var init = function init(dom) {
	console.log('init canvas')
	canvas = document.createElement('canvas')
	canvas.width = Number.parseInt(dom.getAttribute('width'))
	canvas.height = Number.parseInt(dom.getAttribute('height'))
	dom.appendChild(canvas)
	ctx = canvas.getContext('2d')
}

var setOptions = function (data) {
	drawAxis()
	drawLine(data)
}

var drawAxis = function drawAxis() {
	// 画纵轴
	ctx.beginPath()
	ctx.moveTo(OffsetLeft, HEIGHT)
	ctx.lineTo(OffsetLeft, OffsetTop)
	ctx.closePath()
	ctx.stroke()
	// 画横轴
	ctx.beginPath()
	ctx.moveTo(OffsetLeft, HEIGHT)
	ctx.lineTo(WIDTH, HEIGHT)
	ctx.closePath()
	ctx.stroke()
	// 纵轴箭头
	ctx.beginPath()
	ctx.moveTo(OffsetLeft, OffsetTop)
	ctx.lineTo(OffsetLeft - ArrowWidth, OffsetTop)
	ctx.lineTo(OffsetLeft, OffsetTop - ArrowHeight)
	ctx.lineTo(OffsetLeft + ArrowWidth, OffsetTop)
	ctx.lineTo(OffsetLeft, OffsetTop)
	ctx.closePath()
	ctx.fill()
	// 横轴箭头
	ctx.beginPath()
	ctx.moveTo(WIDTH, HEIGHT)
	ctx.lineTo(WIDTH, HEIGHT - ArrowWidth)
	ctx.lineTo(WIDTH + ArrowHeight, HEIGHT)
	ctx.lineTo(WIDTH, HEIGHT + ArrowWidth)
	ctx.lineTo(WIDTH, HEIGHT)
	ctx.closePath()
	ctx.fill()

	// 画垂直纵轴的横向分段线
	for (var i = 0; i < 5; i++) {
		ctx.beginPath()
		ctx.moveTo(OffsetLeft, HEIGHT - (i + 1) * 100)
		ctx.lineTo(WIDTH, HEIGHT - (i + 1) * 100)
		ctx.closePath()
		ctx.strokeStyle = '#b2ebf2'
		ctx.stroke()
		ctx.fillText((i + 1) + 'K', 20, HEIGHT - (i + 1) * 100, 20)
	}
}

var drawLine = function (data) {
	data = data.sort((a, b) => {
		return a.x - b.x
	})

	console.log(data)
	for (var j = 0; j < data.length; j++) {
		ctx.fillRect(50 + (j + 1) * 100 - 5, HEIGHT - data[j].y * 100 - 5, 10, 10)
		ctx.fill()
		const count = j + 1
		rectEvent.push({
			rx: 50 + (j + 1) * 100 - 5,
			ry: HEIGHT - data[j].y * 100 - 5,
			event: function () {
				console.log('点击了第' + count + '个点')
				alert('点击了第' + count + '个点')
			}
		})
	}
	var linePathObj = new Path2D()
	linePathObj.moveTo(50 + (0 + 1) * 100, HEIGHT - data[0].y * 100)
	for (var j = 0; j < data.length; j++) {
		linePathObj.lineTo(50 + (j + 1) * 100, HEIGHT - data[j].y * 100)
		linePathObj.moveTo(50 + (j + 1) * 100, HEIGHT - data[j].y * 100)
	}
	ctx.strokeStyle = '#5d4037'
	ctx.stroke(linePathObj)

	canvas.addEventListener('click', function (event) {
		checkPointIsRect(event.offsetX, event.offsetY)
	})
}



function checkPointIsRect(x, y) {
	console.log(x)
	console.log(y)
	rectEvent.forEach(re => {
		if (x <= re.rx + 10 && x >= re.rx && y <= re.ry + 10 && y >= re.ry) {
			var fn = re.event
			fn()
		}
	})
}